//
//  CategoryIconSelectView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 31.03.25.
//

import SwiftUI

struct CategoryIconSelectView: View {
    let columns: [GridItem] = [
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible())
        ]
    @Binding var selectedGroupTitle: CategoryGroupTitle?
    @Binding var groupTitles: Array<CategoryGroupTitle>
    @Binding var selectedCategoryIconList:Array<CategoryIcon>
    @Binding var selectedCategoryIcon: CategoryIcon?
    @Binding var searchQuery: String
    
    var body: some View {
        if (selectedCategoryIconList.isEmpty) {
            VStack {
                Text("暂无数据").padding(.top , 100)
                Spacer()
            }
        } else {
            HStack (alignment: .top) {
                ScrollView (.vertical) {
                    VStack (spacing: 0) {
                        ForEach(groupTitles) { groupTitle in
                            Button (action: {
                                selectedGroupTitle = groupTitle
                                selectedCategoryIconList = CategoryIconLocalData.getSelectedIconList(title: groupTitle, searchQuery: searchQuery)
                            }) {
                                CategoryGroupTitleView(title: groupTitle, selectedTitleName: selectedTitleName())
                                    .padding(EdgeInsets(top: 8, leading: 20, bottom: 8, trailing: 16))
                            }
                        }
                    }
                }
                ScrollView (.vertical) {
                    LazyVGrid(columns:columns) {
                        ForEach(selectedCategoryIconList.indices, id: \.self) { index in
                            let categoryIcon = selectedCategoryIconList[index]
                            Button(action: {
                                selectedCategoryIcon = categoryIcon
                                // inputCategoryName = categoryIcon.name
                            }) {
                                CategoryGridItemView(categoryIcon: categoryIcon, isSelected: categoryIcon == selectedCategoryIcon).frame(maxWidth: .infinity)
                            }
                        }
                    }
                }
                .frame(maxWidth: .infinity)
                .padding(.trailing, 10)
            }
        }
    }
    
    private func selectedTitleName() -> String {
        if (selectedGroupTitle != nil) {
            return selectedGroupTitle!.name
        } else {
            return ""
        }
    }
}

//#Preview {
//    CategoryIconSelectView()
//}
